package com.dmjj.cad.controller;

import com.dmjj.cad.dto.CategoryDTO;
import com.dmjj.cad.dto.FloorplanDTO;
import com.dmjj.cad.dto.GraphDTO;
import com.dmjj.cad.service.GraphService;
import com.dmjj.cad.vo.*;
import com.dmjj.cadcommon.base.BaseController;
import com.dmjj.cadcommon.result.ResultEnum;
import com.dmjj.cadcommon.result.ResultObject;
import com.dmjj.cadcommon.util.ListCopyToVOUtil;
import com.dmjj.cadcommon.util.PaginationVOUtil;
import com.dmjj.cadcommon.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 元素管理表控制器
 * @Author zhangxue
 * @Date 2019-04-19 10:39:23
 */

@RestController
@Api(tags = "元素管理表控制器")
@RequestMapping("graph")
public class GraphController extends BaseController {

    private static final Log LOGGER = LogFactory.getLog(GraphController.class);

    @Autowired
    private GraphService service;
    @Autowired
    private ResultObject resultObject;

    /**
	 * 元素管理表列表
     * @Author zhangxue
     * @Date 2019-04-19 10:39:23
	 * @Param
	 * @Return
	 */
    @ApiOperation(value = "元素管理表列表", response = GraphVO.class)
    @PostMapping("list4Page")
    public ResultVO<Object> list4Page(
            GraphVO entity,
            @ApiParam(value = "当前页", required = true) @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @ApiParam(value = "每页显示条数", required = true) @RequestParam(value = "pageSize", defaultValue = "15") Integer pageSize
    ){
        try {
            GraphDTO entityDTO = new GraphDTO();
            BeanUtils.copyProperties(entity, entityDTO);
            List<GraphDTO> list = service.list4Page(entityDTO, pageNum, pageSize);
            return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), PaginationVOUtil.getPaginationVO(list, GraphVO.class, pageNum));
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }

    /**
     * 元素管理表列表（无分页）
     * @Author zhangxue
     * @Date 2019-04-19 10:39:23
     * @Param
     * @Return
     */
    @ApiOperation(value = "元素管理表列表（无分页）", response = GraphVO.class)
    @PostMapping("byFloorplanId")
    public ResultVO<Object> listByCondition(GraphQueryVO entity){
        try {
            GraphDTO entityDTO = new GraphDTO();
            BeanUtils.copyProperties(entity, entityDTO);
            List<GraphDTO> list = service.listByCondition(entityDTO);
            return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), ListCopyToVOUtil.getListToVO(list, GraphVO.class));
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }

    /**
     * 元素管理表详细信息
     * @Author zhangxue
     * @Date 2019-04-19 10:39:23
     * @Param
     * @Return
     */
    @ApiOperation(value = "元素管理表详细信息", response = GraphVO.class)
    @PostMapping("byid")
    public ResultVO<Object> queryOneByPk(@ApiParam(value = "id",required = true) @RequestParam(value = "id") Long id){
        try {
            GraphDTO entityDTO = service.queryOneByPk(id);
            GraphVO entity = new GraphVO();
            BeanUtils.copyProperties(entityDTO, entity);
            return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), entity);
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }

    /**
     * 保存元素管理表信息
     * @Author zhangxue
     * @Date 2019-04-19 10:39:23
     * @Param
     * @Return
     */
    @ApiOperation(value = "保存元素管理表信息", response = ResultVO.class)
    @PostMapping("insert")
    public ResultVO<Object> save(GraphInsertVO entity) {
        try {
            if(entity.getFloorplanid()==null){
                return resultObject.error(ResultEnum.FAIL.getCode(), "缺少floorplanid字段");
            }
            if(entity.getName()==null){
                return resultObject.error(ResultEnum.FAIL.getCode(), "缺少name字段");
            }
            if(entity.getType()==null){
                return resultObject.error(ResultEnum.FAIL.getCode(), "缺少type字段");
            }
            if(entity.getX()==null){
                return resultObject.error(ResultEnum.FAIL.getCode(), "缺少 x 字段");
            }
            if(entity.getY()==null){
                return resultObject.error(ResultEnum.FAIL.getCode(), "缺少 y 字段");
            }
            GraphDTO entityDTO = new GraphDTO();
            BeanUtils.copyProperties(entity, entityDTO);
            if(service.save(entityDTO) > 0) {
                return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(),entityDTO);
            }else {
                return resultObject.error(ResultEnum.FAIL.getCode(), ResultEnum.FAIL.getMsg());
            }
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }

    /**
     * 修改元素信息
     * @Author zhangxue
     * @Date 2019-04-19 10:39:23
     * @Param
     * @Return
     */
    @ApiOperation(value = "修改元素信息", response = ResultVO.class)
    @PostMapping("update")
    public ResultVO<Object> update(GraphUpdateVO entity) {
        try {
            if(entity.getFloorplanid()==null){
                return resultObject.error(ResultEnum.FAIL.getCode(), "缺少floorplanid字段");
            }
            if(entity.getName()==null){
                return resultObject.error(ResultEnum.FAIL.getCode(), "缺少name字段");
            }
            if(entity.getType()==null){
                return resultObject.error(ResultEnum.FAIL.getCode(), "缺少type字段");
            }
            if(entity.getX()==null){
                return resultObject.error(ResultEnum.FAIL.getCode(), "缺少 x 字段");
            }
            if(entity.getY()==null){
                return resultObject.error(ResultEnum.FAIL.getCode(), "缺少 y 字段");
            }
            if(entity.getId()==null){
                GraphDTO entityDTO = new GraphDTO();
                BeanUtils.copyProperties(entity, entityDTO);
                if(service.save(entityDTO) > 0) {
                    return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(),entityDTO.getId());
                }else {
                    return resultObject.error(ResultEnum.FAIL.getCode(), ResultEnum.FAIL.getMsg());
                }
            }else{
                GraphDTO entityDTO = new GraphDTO();
                BeanUtils.copyProperties(entity, entityDTO);
                if(service.edit(entityDTO) > 0) {
                    return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(),entityDTO.getId());
                }else {
                    return resultObject.error(ResultEnum.FAIL.getCode(), "无该id");
                }
            }

        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }


    /**
     * 删除元素管理表信息
     * @Author zhangxue
     * @Date 2019-04-19 10:39:23
     * @Param
     * @Return
     */
    @ApiOperation(value = "删除元素管理表信息", response = ResultVO.class)
    @PostMapping("delete")
    public ResultVO<Object> delete(@ApiParam(value = "id",required = true) @RequestParam(value = "id") Long id){
        try {
            if(service.delete(id) > 0) {
                Integer i = service.deleteGraphSon(id);
                if(i>=0){
                    return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg());
                }else{
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return resultObject.success(ResultEnum.FAIL.getCode(), "删除子元素失败");
                }
            }else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return resultObject.success(ResultEnum.FAIL.getCode(), "删除元素失败（无该id）");
            }
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }
    
    
    /**
     * @Author zhangxue
     * @Description //TODO 分类统计列表
     * @Date 9:56 2019/4/23
     * @Param 
     * @return 
     **/
    @ApiOperation(value = "分类统计列表", response = ResultVO.class)
    @PostMapping("categoryList")
    public ResultVO<Object> categoryList(@ApiParam(value = "floorplanid",required = true) @RequestParam(value = "floorplanid") Long floorplanid) {
        try {
            //获取所有与当前floorplanid相同类别的floorplan
            List<Map<String,Object>> floorplanlist = service.queryAllSameCategoryFloorplan(floorplanid);
            String floorPlanIdArr = "";
            if(floorplanlist.size()==0){
                return resultObject.error(ResultEnum.EXCEPTION.getCode(), "无floorplan信息");
            }
            for(int i=0;i<floorplanlist.size();i++){
                String floorPlanId = floorplanlist.get(i).get("id")!=null? floorplanlist.get(i).get("id").toString():null;
                floorPlanIdArr += floorPlanId+",";

            }
            floorPlanIdArr = floorPlanIdArr.substring(0,floorPlanIdArr.length()-1);
            if(floorPlanIdArr==""||floorPlanIdArr==null){
                return resultObject.error(ResultEnum.FAIL.getCode(), "无平面图信息");
            }
            Map<String,Object> floorplanMap = new HashMap<String, Object>();
            floorplanMap.put("floorPlanIdArr",floorPlanIdArr);
            List<Map<String,Object>> graphList = service.queryAllGraphByFloorplan(floorplanMap);
            Double areaarr = 0.0;
            Integer num = graphList.size();
            for(int i=0;i<graphList.size();i++){
                String area = String.valueOf(graphList.get(i).get("area")!=null?graphList.get(i).get("area"):0);
                Double are = Double.valueOf(area);
                areaarr += are;
            }
            String categoryid = String.valueOf(floorplanlist.get(0).get("categoryId"));
            String categoryname = String.valueOf(floorplanlist.get(0).get("categoryname"));
            Map<String,Object> resultMap = new HashMap<String, Object>();
            resultMap.put("categoryId",categoryid);
            resultMap.put("categoryName",categoryname);
            resultMap.put("num",num);
            resultMap.put("area",areaarr);
            return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(),resultMap);
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }

    @ApiOperation(value = "店铺搜索列表", response = ResultVO.class)
    @PostMapping("searchList")
    public ResultVO<Object> categoryList(GraphSearchVO graphSearchVO) {
        if(graphSearchVO.getMax_area()==null){
            return resultObject.error(ResultEnum.FAIL.getCode(), "缺少 max_area 字段");
        }
        if(graphSearchVO.getMin_area()==null){
            return resultObject.error(ResultEnum.FAIL.getCode(), "缺少 min_area 字段");
        }
        if(graphSearchVO.getName()==null){
            return resultObject.error(ResultEnum.FAIL.getCode(), "缺少 name 字段");
        }
        if(graphSearchVO.getCategory()==null){
            return resultObject.error(ResultEnum.FAIL.getCode(), "缺少 category 字段");
        }
        if(graphSearchVO.getCode()==null){
            return resultObject.error(ResultEnum.FAIL.getCode(), "缺少 code 字段");
        }
        //查询符合条件分类并级联查询出所有下属floorplanid 搜索条件为code category
        List<Map<String,Object>> CategoryList = service.queryAllFixCategory(graphSearchVO);
        List<Map<String,Object>> resultList = new ArrayList<Map<String,Object>>();
        for(int i=0;i<CategoryList.size();i++){
            Map<String,Object> categoryMap = CategoryList.get(i);
            categoryMap.put("max_area",graphSearchVO.getMax_area());
            categoryMap.put("min_area",graphSearchVO.getMin_area());
            categoryMap.put("name",graphSearchVO.getName());
            List<Map<String,Object>> graphList = service.queryAllFixGraph(categoryMap);
            for(int j=0;j<graphList.size();j++){
                Map<String,Object> tempMap = graphList.get(j);
                tempMap.put("floorplanId",categoryMap.get("floorplanId"));
                tempMap.put("categoryId",categoryMap.get("categoryId"));
                tempMap.put("categoryName",categoryMap.get("categoryName"));
                resultList.add(tempMap);
            }
        }
        return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(),resultList);
    }
}